#include "woodensolitairescene.h"
#include "drawer.h"
#include "chipplace.h"
#include "chip.h"


WoodenSolitaireScene::WoodenSolitaireScene(int chipSize, const QColor &color) :
    QGraphicsScene()
{
    drawer = new Drawer(chipSize);
    drawer->draw(this, color);
    for(int i = 0; i < places.size(); ++i) addItem(places[i]);
    for(int i = 0; i < chips.size(); ++i) addItem(chips[i]);
}

void WoodenSolitaireScene::addChip(Chip *chip)
{
    chips.push_back(chip);
}

void WoodenSolitaireScene::addPlace(ChipPlace *place)
{
    places.push_back(place);
}

ChipPlace* WoodenSolitaireScene::getPlaceItem(int row, int col){
    int index = drawer->getPlaceIndex(row, col);
    if(index > -1) return places[index];
    else return NULL;
}

bool WoodenSolitaireScene::jump(Chip *chip, ChipPlace *place)
{
    int cRow = chip->getRow(), cCol = chip->getCol();
    int pRow = place->getRow(), pCol = place->getCol();

    if( abs(place->pos().x() - chip->pos().x()) < drawer->getChipSize() &&
        abs(place->pos().y() - chip->pos().y()) < drawer->getChipSize() &&

        (abs(cRow - pRow) == 2 && abs(cCol - pCol) == 0 ||
         abs(cRow - pRow) == 0 && abs(cCol - pCol) == 2)){

        int r, c;
        if(cRow == pRow){
            r = pRow;
            c = (cCol > pCol) ? pCol + 1 : pCol - 1;
        }else{
            c = pCol;
            r = (cRow > pRow) ? pRow + 1 : pRow - 1;
        }
        Chip *chip = getPlaceItem(r, c)->getChipItem();
        if(chip != NULL){
            removeItem(chip);
            return true;
        }
    }
    return false;
}
